require 'rubygems'
require 'fileutils'

# Running JRuby on OS X requires options passed at the start. To pass those
# options and avoid double JVM startup, we want 'shoes' to be a bash script on
# Unix systems, but Rubygems only supports installing Ruby to the bin.

# We work around this by installing our script as shoes-stub, then acting like
# a "native extension" via this Rakefile, we manually generate the right script
# (a copy of shoes-stub) in the Gem.bindir.

# Because we don't actually declare shoes as an executable, we also have to
# copy our shoes.bat into place as well on Windows systems.

# We also provide a Rubygems plugin to clean up our manual file on uninstall.
# Post-install hooks didn't seem to work, though, hence the extension trick.

task default: ['install_script']

task :install_script do
  # If we're run via jruby-complete.jar, bindir is within the jar itself so
  # look for bin based on user directory. Otherwise, prefer Gem.bindir.
  if Gem.bindir.start_with?("uri:classloader")
    dest_dir = Gem.bindir(Gem.user_dir)
  else
    dest_dir = Gem.bindir
  end

  if Gem.win_platform?
    source_path = File.join(Dir.pwd, "shoes.bat")
    dest_path = File.join(dest_dir, "shoes.bat")
  else
    source_path = File.join(Dir.pwd, "..", "..", "bin", "shoes-stub")
    dest_path = File.join(dest_dir, "shoes")
  end

  FileUtils.mkdir_p(dest_dir)
  FileUtils.cp(source_path, dest_path)
end
